package com.icongyou.enterprise.talent_analysis.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icongyou.enterprise.talent_analysis.entity.WordCloudCache;
import com.icongyou.enterprise.talent_analysis.entity.WordCloudUpdateQueue;
import com.icongyou.enterprise.talent_analysis.mapper.WordCloudCacheMapper;
import com.icongyou.enterprise.talent_analysis.mapper.WordCloudUpdateQueueMapper;
import com.icongyou.enterprise.talent_analysis.service.AIPortraitEvaluationService;
import com.icongyou.enterprise.talent_analysis.service.WordCloudService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 词云图服务实现（独立于画像服务）
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WordCloudServiceImpl implements WordCloudService {
    
    private final WordCloudCacheMapper cacheMapper;
    private final WordCloudUpdateQueueMapper queueMapper;
    private final AIPortraitEvaluationService aiPortraitService;
    private final ObjectMapper objectMapper;
    
    @Override
    public Map<String, Integer> getWordCloud(String studentId) {
        
        // 1. 查询缓存
        WordCloudCache cache = cacheMapper.selectByStudentId(studentId);
        if (cache != null) {
            return parseKeywords(cache.getKeywordsJson());
        }
        
        // 2. 缓存未命中，同步生成
        return generateWordCloudSync(studentId);
    }
    
    @Override
    public void generateWordCloudAsync(String studentId, String triggerType, String triggerSource) {
        
        WordCloudUpdateQueue task = new WordCloudUpdateQueue();
        task.setStudentId(studentId);
        task.setTriggerType(triggerType);
        task.setTriggerSource(triggerSource);
        task.setCreatedAt(LocalDateTime.now());
        
        queueMapper.insert(task);
    }
    
    @Override
    public Map<String, Integer> generateWordCloudSync(String studentId) {
        
        try {
            // 1. 调用AI提取关键词
            Map<String, Integer> keywords = aiPortraitService.extractTeacherCommentKeywords(studentId);
            
            if (keywords == null || keywords.isEmpty()) {
                return new HashMap<>();
            }
            
            // 2. 保存到缓存
            String keywordsJson = objectMapper.writeValueAsString(keywords);
            saveCache(studentId, keywordsJson, true);
            
            return keywords;
            
        } catch (Exception e) {
            return new HashMap<>();
        }
    }
    
    @Override
    public void invalidateCache(String studentId) {
        cacheMapper.deleteByStudentId(studentId);
    }
    
    /**
     * 保存缓存
     */
    private void saveCache(String studentId, String keywordsJson, boolean aiUsed) {
        WordCloudCache existing = cacheMapper.selectByStudentId(studentId);
        LocalDateTime now = LocalDateTime.now();
        
        if (existing == null) {
            // 插入新缓存
            WordCloudCache cache = new WordCloudCache();
            cache.setStudentId(studentId);
            cache.setKeywordsJson(keywordsJson);
            cache.setAiUsed(aiUsed);
            cache.setGeneratedAt(now);
            cache.setUpdatedAt(now);
            cache.setVersion(0);
            cacheMapper.insert(cache);
        } else {
            // 更新现有缓存
            existing.setKeywordsJson(keywordsJson);
            existing.setAiUsed(aiUsed);
            existing.setUpdatedAt(now);
            int updated = cacheMapper.update(existing);
            if (updated > 0) {
            } else {
            }
        }
    }
    
    /**
     * 解析关键词JSON
     */
    private Map<String, Integer> parseKeywords(String keywordsJson) {
        try {
            return objectMapper.readValue(keywordsJson, new TypeReference<Map<String, Integer>>() {});
        } catch (Exception e) {
            return new HashMap<>();
        }
    }
}
